package com.daervin.svc.parser.sub;

import com.daervin.svc.common.constants.Constants;
import com.daervin.svc.common.dto.NewsDTO;
import com.daervin.svc.common.utils.DateTimeUtils;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;

import java.util.Calendar;

import static com.daervin.svc.common.constants.SourceEnum.JIE_MIAN;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
public class JiemianSubPageParser extends RootSubParser {

    public JiemianSubPageParser(String... listUrl) {
        super(listUrl);
    }

    @Override
    public MatchOther processPage(Page page) {
        Html html = page.getHtml();
        if (html == null) {
            return MatchOther.NO;
        }
        Calendar now = Calendar.getInstance();
        String today = DateTimeUtils.shortParse(now.getTime());
        String todayNow = DateTimeUtils.longParse(now.getTime());
        now.add(Calendar.DAY_OF_MONTH, -1);
        String yesterday = DateTimeUtils.shortParse(now.getTime());

        String title = html.xpath("//div[@class='article-header']/h1/text()").get();
        String desc = html.xpath("//div[@class='article-content']/p/text()").get();
        String footer = html.xpath("//div[@class='article-info']/p[@class='info-s']/span[@class='date']/text()").get();
        if (!StringUtils.isEmpty(footer)) {
            if (footer.contains("刚刚") || footer.contains("分钟") || footer.contains("小时")) {
                footer = todayNow;
            } else if (footer.contains("今天")) {
                footer = footer.replaceAll("今天", "").trim();
                footer = today + " " + footer;
            } else if (footer.contains("昨天")) {
                footer = footer.replaceAll("昨天", "").trim();
                footer = yesterday + " " + footer;
            } else {
                footer = footer.replaceAll("/", "-");
            }
        }
        if (StringUtils.isEmpty(desc) || StringUtils.isEmpty(title) || StringUtils.isEmpty(footer)) {
            return MatchOther.NO;
        }
        NewsDTO news = new NewsDTO();
        news.setDesc(desc);
        news.setTitle(title);
        news.setBelongDate(footer);
        news.setLinks(page.getRequest().getUrl());
        news.setAnnouncer(JIE_MIAN.announcer);
        Integer category = (Integer) page.getRequest().getExtra("category");
        news.setCategory(category == null ? 0 : category);

        page.putField(Constants.PARSER_RESULT_ITEM, news);
        return MatchOther.YES;
    }

}